
import React, { useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom/client';
import { getAuthAxios } from '../lib/authAxios.js';
import { message } from 'antd';
// 营业厅受理
const RootComponent = () => {
    const myAxios = getAuthAxios();
    var tabNavDom = useRef(null)
    useEffect(() => {
        getDomPolling()
        function onGlobalVarChange(e) {
            getDomPolling()
        }
        window.addEventListener("MY_GLOBAL_VAR_CHANGE", onGlobalVarChange)
        return () => window.removeEventListener("MY_GLOBAL_VAR_CHANGE", onGlobalVarChange)
    }, []);
    var requireList;
    var formItemList;
    var formData = {};
    //   判断是 是从业扩进来的
    const isYeKuo = (iframe) => {
        let flag = false
        let topBreadWrap = iframe.querySelector("#app > div.bread-wrap > div.bread-root")
        if (!topBreadWrap) return
        let str = topBreadWrap.innerText
        // 1. 按换行符分割
        const lines = str.split('\n');
        // 2. 清理每个子字符串
        const result = lines
            .map(line => line.replace(/\//g, '').trim())  // 替换斜杠并去空格
            .filter(Boolean);  // 过滤空字符串
        if (result[0] == '业扩接入' && result[1] == '获得电力' && result[2] == '低压非居民新装增容' && result[3] == '营业厅受理') {
            flag = true
        }
        return flag
    }
    const getDomPolling = () => {
        const mainBox = document.querySelector('.main-container-view')
        if (!mainBox) return
        observeChanges(mainBox, iFdom => {
            const iframeDomList = document.querySelectorAll('iframe')
            iframeDomList.forEach((item, index) => {
                console.log("jieguo", isYeKuo(item.contentDocument || item.contentWindow.document))
                if (!isYeKuo(item.contentDocument || item.contentWindow.document)) return
                const computedStyle = window.getComputedStyle(item)
                const displayValue = computedStyle.display;
                if (displayValue == 'block') {
                    if (!item) { return }
                    // item.onload = () => {
                    const iframeDom = item.contentDocument || item.contentWindow.document
                    let tabNav = iframeDom.querySelector('.jxm-tab-nav >.nav-scroll-wrap')
                    tabNavDom = tabNav
                    observeSave(iframeDom)
                    observeUpload(iframeDom)
                    observeChanges(iframeDom, iframe => {
                        requireList = iframeDom.querySelectorAll('.is-required>label')
                        requireList.forEach(i => i.style.backgroundColor = 'rgb(252,241,118)')
                        formItemList = iframeDom.querySelectorAll('.el-form-item')
                        setTimeout(() => {
                            let tempformData = {}
                            formItemList.forEach(item => {
                                if (item.querySelector('input')) {
                                    formData[item.children[0].textContent] = {
                                        value: item.querySelector('input').value,
                                        dom: item.querySelector('input')
                                    }
                                }
                            })
                            if (Object.keys(tempformData).length > 0) {
                                formData = tempformData
                            }
                        }, 1000)
                        // console.log("formData===================", formData)
                        const tabNav = iframeDom.querySelector('.jxm-tab-nav >.nav-scroll-wrap')
                        console.log('tabNavtabNavtabNavtabNavtabNavtabNav', tabNav)
                        if (tabNav) {
                            handleBtn(tabNav)
                        }
                    }, { attributes: false })
                    // }


                }

            })

        }, { attributes: true })
    }
    const checkAddress = (val1, val2, inputDOM) => {
        if (!checkAddress.successFlag) {
            checkAddress.successFlag = { count: 0, total: 0, failCount: 0 };
        }
        checkAddress.successFlag.total += 1;
        myAxios.post('http://10.158.212.196:34002/yxjc/api/yxjc/v1/yxjcAreaWide/list', { "streetName": val1, "communityName": val2 })
            .then(response => {
                console.log('数据已成功发送:', response.data);
                if (response.data.data.list.length > 0) {
                    checkAddress.successFlag.count += 1;
                    if (checkAddress.successFlag.count === checkAddress.successFlag.total) {
                        message.success("地址信息校验通过");
                        // 重置，防止后续多次提示
                        checkAddress.successFlag = { count: 0, total: 0 };
                    }
                    console.log('通过')
                } else {
                    checkAddress.successFlag.failCount += 1;
                    inputDOM.style.backgroundColor = 'rgb(230, 75, 70)'
                    if (checkAddress.successFlag.failCount === checkAddress.successFlag.total) {
                        message.warning("地址信息校验不通过");
                        // 重置，防止后续多次提示
                        checkAddress.successFlag = { count: 0, total: 0, failCount: 0 };
                    }
                    saveWarningData(addressWarningObj)
                }
            })
            .catch(error => {
                console.error('发送数据失败:', error);
                message.warning("由于网络问题，地址信息未能校核")
            })
        return;
    }
    const saveWarningData = (saveWarningData) => {
        console.log(saveWarningData, "saveWarningDatasaveWarningData")
        myAxios.post('http://10.158.212.196:34002/yxjc/api/yxjc/v1/yxjcRemindMsg/addBatch', [saveWarningData])
            .then(response => {
                console.log('数据已成功发送:', response.data);
            })
            .catch(error => {
                console.error('发送数据失败:', error);
            })
    }
    const handleAddress = (str, inputDOM) => {
        const addressRegex = /^(.+?省)|(.+?市)(.+?[市区县])(.+?街道|.+?镇|.+?乡)(.+?村委会|.+?居委会)(.*)$/;
        const match = str.match(addressRegex)
        if (match) {
            const [, province, city, district, street, committee, detail] = match;
            return checkAddress(street, committee, inputDOM)

        }
        return false;
    }

    const handleBtn = (pdom) => {
        const child = pdom.querySelector("#_address-btn")
        if (child) {
            return
        }
        const btn = document.createElement('button');
        btn.style.position = 'absolute';
        btn.style.top = '0';
        btn.style.left = '330';
        btn.style.zIndex = '999';
        btn.style.backgroundColor = '#4caf50';
        btn.style.color = 'white';
        btn.style.border = 'none';
        btn.style.padding = '10px 20px';
        btn.style.cursor = 'pointer';
        btn.textContent = '一键复核';
        btn.style.borderRadius = '5px';
        btn.opacity = '0.5';
        btn.id = '_address-btn'
        btn.addEventListener("click", () => {
            // message.success("复核中，请稍后")
            formItemList.forEach(i => {
                if ('地址信息' == i.title) {
                    let msg = i.querySelector("input").title
                    const inputDOM = i.querySelector("input")
                    handleAddress(msg, inputDOM)
                }

            })
        });
        pdom.appendChild(btn)
    }
    /**OCR 识别 */

    function handleFileUpload(e) {
        const files = e.target.files;
        console.log('文件上传事件触发', files.length);
        if (files && files.length > 0) {
            const form = new FormData();
            const es = Array.from(files).filter(file => file.size > 0);

            es.forEach(async (file) => {
                if (file.type.startsWith('image/')) {
                    // 图片直接封装
                    form.append('file', file);
                    console.log('图片已封装:', file);
                } else if (file.type === 'application/pdf') {
                    // PDF转图片
                    const images = await pdfToImages(file);
                    images.forEach((imgBlob, idx) => {
                        form.append('file', imgBlob, `page${idx + 1}.png`);
                        console.log('PDF转图片已封装:', imgBlob);
                    });
                } else {
                    console.log('不支持的文件类型:', file.type);
                }
            });

            checkOCR(form)
        }

    }
    const observeUpload = (dom) => {
        dom.addEventListener('change', function (e) {
            console.log('uploadChange')
            const input = e.target;
            if (
                input &&
                input.tagName === 'INPUT' &&
                input.type === 'file'
            ) {
                handleFileUpload(e);
            }
        }, true);
    };
    async function pdfToImages(pdfFile) {

        const pdfjsLib = window.pdfjsLib;
        const arrayBuffer = await pdfFile.arrayBuffer();
        const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
        const images = [];
        for (let i = 1; i <= pdf.numPages; i++) {
            const page = await pdf.getPage(i);
            const viewport = page.getViewport({ scale: 2 });
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            canvas.width = viewport.width;
            canvas.height = viewport.height;
            await page.render({ canvasContext: context, viewport }).promise;
            // canvas转blob
            const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));
            images.push(blob);
        }
        return images;
    }

    const observeSave = (dom) => {
        dom.addEventListener('click', function (e) {
            const btn = e.target;
            if (
                btn &&
               ( btn.textContent == '保存' || btn.textContent == '发送')
            ) {
                const child = dom.querySelector("#_address-btn")
                child && child.click()
            }
        }, true);
    };
    const checkOCR = (formData) => {
        myAxios.post('http://10.158.212.196:34002/yxjc/api/v1/yxjcocr/idcard', formData)
            .then(response => {
                console.log('数据已成功发送:', response.data);
                if (response && response.data) {
                    checkUserName(response.data.data['姓名'])
                    checkIndustry(response.data.data['行业分类'])
                }

            })
            .catch(error => {
                console.error('发送数据失败:', error);
            })
    }
    const checkUserName = (userName) => {
        if (userName == formData['客户名称'].value) {
            console.log('通过')
            message.success('客户名称校验通过')
        } else {
            message.warning('客户名称与上传文件不一致')
        }

    }
    const checkIndustry = (industryName) => {
        if (industryName == formData['行业分类'].value) {
            console.log('通过')
            message.success('行业分类校验通过')
        } else {
            message.warning('行业分类与上传文件不一致')
        }

    }
    return (null);
};



const init = () => {
    if (document.getElementById("self-div-check")) {
        return
    }
    const container = document.createElement('div');
    container.id = 'self-div-check'
    container.style.fontSize = '14px';
    document.body.appendChild(container)
    const root = ReactDOM.createRoot(container);
    root.render(<RootComponent />);

}

init()
